import {Command} from '../constant';
import Taro from '@tarojs/taro';
import moment from 'dayjs';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import {addressInfo} from '@/utils/location/area/area';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      let {orderId, type} = getData().main;
      let daysArr = [],
        cont = 0;
      //获取当前7天数据
      let sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - cont);
      for (let i = 0; i <= 6; i++) {
        let obj = {name: ''};
        const date = new Date(sevenDaysAgo);
        date.setDate(sevenDaysAgo.getDate() + i);
        obj.name = moment(date).format('YYYY-MM-DD');
        daysArr.push(obj);
      }
      action.commonChange('main.daysArr', daysArr);
      if (type == 'edit') {
        action.getWhaleOrderId(orderId);
      }
    },
    //地址初始化
    async _addressInit() {
      const context = await api.customerDeliveryAddressBaseController.findAddressList();
      let address: any = {};
      let defaltAddress;
      if (context.length) {
        //过滤默认地址
        // const defaltAddress = context.filter((item) => item.isDefaltAddress === 1)[0];
        for (let i = 0; i < context.length; i++) {
          const item = context[i];
          const addressInfoStr = await addressInfo(item.provinceId, item.cityId, item.areaId, item.streetId);
          item.addressInfo = addressInfoStr + item.deliveryAddress;
          if (item.isDefaltAddress != 0) {
            defaltAddress = item;
          }
        }
        //没有默认地址取第一个
        address = defaltAddress || context[0];
      }

      // 校验是否需要完善地址
      if (address && address.deliveryAddressId) {
        const result = await api.platformAddressController.verifyAddress({
          provinceId: address.provinceId,
          cityId: address.cityId,
          areaId: address.areaId,
          streetId: address.streetId,
        });
        if (result) {
          address.needComplete = true;
        }
      }
      return address;
    },
    //查询订单详情
    async getWhaleOrderId(orderId) {
      let {list} = getData().main;
      let result = await api.OnecategoryController.getWhaleOrderId(orderId);
      let address = {
        addressInfo: '',
        areaName: '',
        cityName: '',
        consigneeName: '',
        consigneeNumber: '',
        provinceName: '',
      };
      if (result.code == 'K-000000') {
        address.addressInfo = result.context.address;
        address.areaName = result.context.district;
        address.cityName = result.context.city;
        address.consigneeName = result.context.name;
        address.consigneeNumber = result.context.mobile;
        address.provinceName = result.context.province;
        action.commonChange('main.address', address);
        let listSelected;
        list.map((item, Index) => {
          if (item.name == result.context.weight) {
            listSelected = Index;
          }
        });
        action.commonChange('main.listSelected', listSelected);
        action.commonChange('main.orderNo', result.context.orderNo);
      }
    },
    //提交
    async whaleorderAdd() {
      let storeId = Taro.getStorageSync('storeId');
      let {
        dateTime,
        remarks,
        list,
        listSelected,
        dateModel,
        checked,
        daysArr,
        timeArr,
        daysSelected,
        timeSelected,
        remarksModel,
        successModel,
        address,
      } = getData().main;
      let memberType;
      let isAquamarineMember = Taro.getStorageSync('isAquamarineMember');
      let isCrystalMember = Taro.getStorageSync('isCrystalMember');
      if (isAquamarineMember && isCrystalMember) {
        //双会员
        memberType = 2;
      } else if (isAquamarineMember && !isCrystalMember) {
        //蓝晶会员
        memberType = 0;
      } else if (!isAquamarineMember && isCrystalMember) {
        //赤晶会员
        memberType = 1;
      }
      let param = {
        address: address?.addressInfo, //详细地址
        // brandendtime: "",//上门的结束时间
        brandnote: remarks, //用户备注信息
        // brandtime: "",//上门的开始时间
        city: address?.cityName, //市
        district: address?.areaName, //区
        memberType: memberType, //会员类型：0-蓝晶会员 1-赤晶会员 2双会员
        mobile: address?.consigneeNumber, //手机号
        name: address?.consigneeName, //用户姓名
        province: address?.provinceName, //省
        reservationDate: daysArr[daysSelected].name, //预约时间
        storeId: storeId,
        type: 'clothes', //book,clothes
        version: '2', //版本
        weight: list[listSelected].name, //5-10KG,5-10本
      };
      let result = await api.OnecategoryController.whaleorderAdd(param);
      if (result.code == 'K-000000') {
        // Taro.showToast({
        //   title: '提交成功！',
        //   icon: 'none',
        //   duration: 2000,
        // });
        // Taro.navigateTo({
        //   url: '/pages/package-D/equityOrders/index',
        // });
        action.commonChange('main.successModel', true);
      }
    },
    //修改
    async whaleorderEdit() {
      let storeId = Taro.getStorageSync('storeId');
      let {
        dateTime,
        remarks,
        list,
        listSelected,
        dateModel,
        checked,
        daysArr,
        timeArr,
        daysSelected,
        timeSelected,
        remarksModel,
        successModel,
        address,
        orderId,
      } = getData().main;
      let param = {
        whaleOrderId: orderId,
        address: address?.addressInfo, //详细地址
        // brandendtime: "",//上门的结束时间
        // brandnote: remarks, //用户备注信息
        // brandtime: "",//上门的开始时间
        city: address?.cityName, //市
        district: address?.areaName, //区
        memberType: 0, //会员类型：0-蓝晶会员 1-赤晶会员 2双会员
        mobile: address?.consigneeNumber, //手机号
        name: address?.consigneeName, //用户姓名
        province: address?.provinceName, //省
        reservationDate: daysArr[daysSelected].name, //预约时间
        storeId: storeId,
        type: 'clothes', //book,clothes
        version: '2', //版本
        weight: list[listSelected].name, //5-10KG,5-10本
      };
      let result = await api.OnecategoryController.whaleorderEdit(param);
      if (result.code == 'K-000000') {
        // Taro.showToast({
        //   title: '修改成功！',
        //   icon: 'none',
        //   duration: 2000,
        // });
        // Taro.navigateTo({
        //   url: '/pages/package-D/equityOrders/index',
        // });
        action.commonChange('main.successModel', true);
      }
    },
    //取消
    async cancelWhaleorder() {
      let {orderNo} = getData().main;
      let result = await api.OnecategoryController.cancelWhaleorder({orderNo});
      if (result.code == 'K-000000') {
        action.commonChange('main.cancelModel', false);
        Taro.showToast({
          title: '取消成功！',
          icon: 'none',
          duration: 2000,
        });
        Taro.navigateTo({
          url: '/pages/package-D/communityService/index',
        });
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageDClothingReservation'),
  };
}

//create by moon https://github.com/creasy2010/moon
